import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { UserService } from '@services/user.service';
import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { Router } from '@angular/router';
import { WindowService } from '@services/window.service';

@Injectable({
  providedIn: 'root'
})
export class LoginAuthGuard implements CanActivate {
  constructor(private userServe: UserService, private router: Router, private windowServe: WindowService) {}
  canActivate(
    next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.userServe.user$.pipe(switchMap(user => {
      if (user) {
        this.router.navigateByUrl('/home/heroes').then(() => {
          this.windowServe.alert('您已登录，无需重复登录');
        });
        return of(false);
      }
      return of(true);
    }));
  }
}
